Skip to content

fix(gateway): preserve legacy behavior with explicit compatibility warnings - #2925

Open
NeverENG wants to merge 15 commits into
oceanbase:masterfrom
NeverENG:fix/gateway-1.6-compat
Open

NeverENG wants to merge 15 commits into
oceanbase:masterfrom
NeverENG:fix/gateway-1.6-compat

Conversation

@NeverENG

@NeverENG NeverENG commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Which issue or RFC does this PR close?

Related to #2460. This delivers an opt-in target-binding path and preserves existing deployment behavior; it does not claim to complete every part of #2460.

Rationale for this change

Core checks a configured target profile while Gateway can send to a separately configured URL. Those destinations need an explicit binding. Enforcing that requirement on every existing deployment would stop model traffic for older Core installations and existing subscription configurations. This PR provides a deliberate migration path with observable warnings.

What changes are included in this PR?

  • Default/unset PC_GATEWAY_TARGET_BINDING=compatible preserves configured URLs, existing two-phase checks, ambient model proxies, and supported subscription operation. A capable Core does not silently change destinations or require new service roles. Startup logs warn that the actual destination is not bound to the Core profile; this warning does not add a migration prerequisite.
  • Explicit PC_GATEWAY_TARGET_BINDING=required requires target capability discovery and a confirmed enforced service identity. Initial and retry admission must return a valid endpoint and matching protocol. Missing target fields, failed discovery, or rejected identity never fall back to Gateway URLs or degraded sends. Subscription credentials retain their destination constraints; Claude CLI rejects required mode because its internal sends cannot be observed.
  • PC_GATEWAY_DEGRADE=passthrough retains its existing compatible-mode restriction to a confirmed non-enforcing Core. One startup warning reports whether that fallback is permitted or inactive based on actual discovery. Explicit Core denials remain blocked. Required mode treats the setting as pause and warns.
  • Model HTTP proxy behavior stays compatible with current master. PC_GATEWAY_UPSTREAM_PROXY=direct|<url> provides explicit overrides. Configuration is validated at startup rather than exiting inside the transport constructor. Warnings describe configured proxy trust without logging proxy values; Core RPC remains direct and redirects are not followed.
  • Missing Core credentials and loopback model listeners without a Gateway key remain supported. Unauthenticated loopback access warns that local processes can invoke model routes. Explicitly empty/invalid Gateway keys reject startup. Shared Gateway/Core credentials remain accepted with a warning in compatible mode and are rejected in required mode.
  • Real-Core acceptance now runs in the existing Gateway CI job. English/Chinese deployment docs and Gateway subscription docs describe both modes and the HTTP/HTTPS proxy boundary. Warnings are operational logs, not a new per-call evidence field.
  • Reconciles the branch with master 1a34cdc53095960f9102729171aa8bf5867ee6a3. The Gateway job retains both target-binding acceptance and the reusable process fixture. Both subproject lockfiles include the root website dependency-group metadata without package version/hash changes. Optional homepage browser dependencies remain optional for default checks and mandatory for website acceptance. Gateway startup retries only deterministic AddrInUse failures within the original startup budget.

Are there any user-facing changes?

Existing deployments can retain their configuration under the default compatible mode. Strict binding is an explicit opt-in requiring configured Core profiles, enforced access control, a service identity, and the documented Server/Scope roles. An invalid or explicitly empty mode/key is a startup configuration error.

Compatible mode does not guarantee destination equality. Ambient or explicitly selected proxies are trusted deployment infrastructure: an HTTP proxy can read model bodies and credentials; an HTTPS CONNECT proxy observes connection metadata, and TLS interception expands that trust. Set PC_GATEWAY_UPSTREAM_PROXY=direct to disable proxy inheritance. Target binding does not authenticate a proxy or establish provider account/region identity.

How was this change tested?

Local validation on head 78c9b1d8552ed4136ab708078d073594b2861ce3 after merging master 1a34cdc53095960f9102729171aa8bf5867ee6a3:

  • cargo +1.95.0 fmt --manifest-path gateway/Cargo.toml --all --check passed.
  • cargo +1.95.0 clippy --locked --manifest-path gateway/Cargo.toml --all-targets -- -D warnings passed.
  • cargo +1.95.0 test --locked --manifest-path gateway/Cargo.toml --workspace passed, including 47 real-binary Gateway behavior tests, 111 executor semantics tests and real-Core RPC recovery acceptance.
  • Real Gateway proxy round trips cover ambient inheritance, explicit proxy precedence, direct mode and NO_PROXY, checking request bodies, provider credentials, two-phase gating, JSON/SSE delivery and unchanged upstream 429 responses.
  • Core-disconnection cases cover Chat and Responses with ordinary and streaming clients. Allowed fallback is marked and memory-free; enforcing Core outages and explicit send/release denials cannot bypass gating.
  • Required-mode listener tests cover missing initial targets, protocol mismatches, missing retry targets, and retry admission to a newly approved endpoint. Configured Gateway URLs receive no requests; release checks carry the latest send binding.
  • make check passed, including all three lockfile checks, pre-commit hooks, type checks, runner routing and integration checks. Scope audit and git diff --check passed.
  • The Gateway CI process-test command passed locally: 61 passed, 1 skipped because this macOS host cannot bind the arbitrary IPv4 loopback alias. It exercises target binding, authentication, the reusable process fixture and HTTP/1 lifecycle against actual Gateway/Core processes.
  • Homepage browser-test collection succeeds with the website dependency group (18 tests). Without that group, default collection skips; required website acceptance fails collection if Playwright is absent.
  • make docs-test passed, including website lint/tests, link validation, production build and verification of 1148 public pages and their internal links.

These checks combine real Gateway/Core processes with local listeners and controlled Core/provider fixtures. They do not establish live external-provider or subscription-host acceptance, or compatibility with an installed historical Core release. Compatible mode intentionally retains Gateway URLs and does not prove destination equality; the English/Chinese installation docs describe each mode's destination source and fallback boundary.

Exact-head CI and its GitHub-tested merge result must finish before claiming CI success. Queued, running or skipped checks are not passed checks.

AI usage statement

Developed with AI assistance: prior work used Claude Opus 5.5; target-binding compatibility changes and validation used OpenAI Codex.

Keep every configuration that works on the 1.6.0 release running, while
retaining the Core-approved target guarantees whenever Core can serve them.
oceanbase#2630 landed after v1.6.0 but v1.6.0 already shipped the gateway, so refusing
legacy destinations, mandatory tokens, and dropped proxy egress are
compatibility breaks for released deployments.

- Derive a target posture at startup: bound when Core advertises target
  resolution and access control is enforced for a service principal,
  compatible when an explicit destination is configured, paused when no
  target can be approved (model routes stay disabled).
- Keep the fail-closed behavior behind the opt-in
  PC_GATEWAY_TARGET_BINDING=required.
- Accept PC_GATEWAY_UPSTREAM_URL* and PC_GATEWAY_DEGRADE again; passthrough
  is downgraded to pause with a warning.
- Make PC_GATEWAY_CORE_TOKEN optional and restore the optional loopback
  client key; when both are configured they must still differ.
- Default the Responses profile to the Chat profile instead of returning 501.
- Request Core target resolution only in bound posture so Core keeps the
  1.6.0 verdict shape everywhere else, and assert a configured destination
  against the approved endpoint with URL semantics instead of rejecting it.
- Inherit ambient proxies by default (1.6.0); PC_GATEWAY_UPSTREAM_PROXY=direct
  ignores them (oceanbase#2630 hardening) and PC_GATEWAY_UPSTREAM_PROXY=<url> routes
  through an explicit trusted hop.
Advertise "powercontext.context-target.v1" in context_protection.check_versions
only when a bound deployment can exist: access control is enforced and Core-side
target profiles are configured.

check_versions is a free-form string array in the OpenAPI contract, so this is
additive: gateways that do not know the token ignore it, and older Core never
emits it. Gateways use it to derive their startup target posture instead of
discovering an unusable binding per request.
Assert the compatibility promises directly: legacy upstream URLs still start
the gateway, a loopback listener starts without a client key, credentials are
rejected only when they are unsafe, and a missing core token no longer blocks
startup.
Describe the bound/compatible/paused posture, the opt-in
PC_GATEWAY_TARGET_BINDING switch, the optional core token and loopback key, the
Responses profile default, and the proxy behavior in both languages.
In `bound` posture Core is the only destination source: the approved endpoint
wins, and a leftover PC_GATEWAY_UPSTREAM_URL* value is ignored instead of being
asserted against it. Operators migrating to Core target profiles therefore do
not have to keep both the Core profile and a legacy gateway URL in sync, and a
stale legacy value can no longer pause sends once Core can resolve targets.

The credential-to-endpoint assertion stays in place for subscriptions, where a
provider credential must never travel to an endpoint other than the one Core
approved for that subscription. Plain routes pass no credential target, so the
assertion no longer fires for legacy URLs that are merely stale.

`compatible` posture keeps the 1.6.0 behavior: the explicitly configured URL is
the send destination, and `PC_GATEWAY_TARGET_BINDING=required` still fails
startup instead of running unbound.

Tested with cargo fmt/clippy/test (all suites green), ruff, and the gateway e2e
suites.
…rmed

A Core that advertises context-target.v1 but fails the startup identity
probe (timeout, 5xx, decode error) was treated as not supporting binding,
so a deployment with a stale legacy URL dropped to compatible posture and
sent model bytes plus provider credentials to that URL for the rest of the
process lifetime.

Split the startup probe into confirmed, unavailable and unverified. Only a
confirmed absence of the capability (or a confirmed non-service identity)
may fall back to compatible; an unverified advertised capability pauses
model routes and fails startup under PC_GATEWAY_TARGET_BINDING=required.
The acceptance module skipped itself when gateway/target/debug/pc-gateway
was absent and otherwise ran a restored CI artifact, so a stale binary
could mask source changes (the 3.12 shard exercised an old build that still
required PC_GATEWAY_CORE_TOKEN). Build the checkout in a module fixture.
@NeverENG

Copy link
Copy Markdown
Collaborator Author

Follow-up on the review findings — all three are now actually fixed in code, not just answered:

  • executor.rs admission requirement: covered by bcf704a35 — in bound posture ManagedCall::target_url is empty, so an allow without both target fields returns unbound_send_without_local_target before transport handoff.
  • main.rs downgrade after a failed identity probe: fixed in 0d1747a98. The startup probe is now tri-state: Confirmed → bound; Unavailable (capability not advertised, /v1/access/me 404, or a confirmed non-service / non-enforced identity) → compatible/paused; Unverified (timeout, 5xx, rejection other than 404, decode error on an advertised capability) → paused, and PC_GATEWAY_TARGET_BINDING=required exits 2 with a distinct message. A transient /v1/access/me failure can no longer turn an advertised capability into an unbound send to a stale legacy URL.
  • tests/e2e/test_gateway_target_real_process.py build: fixed in 73fa1c97b. The module now builds the checkout in an autouse fixture (skips only when cargo is absent) and no longer decides coverage from an import-time pc-gateway file check.

Verified on 73fa1c97b: cargo fmt --check, cargo clippy --all-targets, cargo test -p pc-gateway-app (69/1/13/1/3/30 green), pytest tests/e2e/test_gateway_target_real_process.py (12 passed), ruff clean.

Extract the access probe mapping so it can be exercised without a live
Core, and assert that only a confirmed service identity enables binding,
that 404 is a confirmed absence, and that a failed or rejected discovery of
an advertised capability stays unverified. Also cover the fail-closed
startup for PC_GATEWAY_TARGET_BINDING=required.
Comment thread docs/en/docs/operate/install-gateway.md Resolved
@NeverENG

Copy link
Copy Markdown
Collaborator Author

[P2] The PR description says the compatible fallback "marks the evidence", but the evidence stream cannot distinguish an unbound send

The diff does not touch the evidence crate: CallEvidence has no posture/unbound field, and evidence_process.rs only gained the fixture advertisement for the capability token. The only record of an unbound send is the startup WARN log. Either add a posture/unbound marker to the evidence JSONL, or soften the description to "logs a startup warning".

@NeverENG NeverENG changed the title fix(gateway): keep 1.6.0 deployments compatible while preserving Core-bound targets fix(gateway): preserve diagnostic startup with mandatory Core-bound sends Nov 30, 2026

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default ambient-proxy behavior still violates the approved-destination boundary. I reproduced it with the real Core and Gateway and added the evidence to the existing discussion: #2925 (comment). Please address that P1 before merging.

@hidb4ai
hidb4ai dismissed their stale review December 2, 2026 02:09

Superseded after verifying master reverted #2630 in d426e2d. Ambient proxy inheritance is now documented baseline behavior; the prior reproduction remains valid, but its classification as a new P1 regression is withdrawn. Merge conflicts and final-result validation remain outstanding.

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Head remains 52b9d6218416b60923d0b6e8c425d2c81d321916. Current master reverted #2630; please reconcile the intended target-binding behavior with that rollback. git merge-tree against master 753a546f1805d9ec293e298748a836f8814d4500 reports 36 conflicted files, including ingress, startup, Executor and target acceptance tests. CI now passes for the existing revision, but it does not validate the unresolved merge result. Please update against master, resolve the behavior and documentation consistently, and rerun real Core/Gateway target and authentication acceptance on the resolved commit. I am withdrawing my old proxy-regression P1 classification in the existing thread; no approval is given. The PR still adds configuration/capability interfaces and has no database-table or migration changes.

@hidb4ai hidb4ai added module:core Core: PR changes under src/ module:gateway Primary module: model gateway, protocols and context injection labels Dec 2, 2026
@NeverENG NeverENG changed the title fix(gateway): preserve diagnostic startup with mandatory Core-bound sends fix(gateway): preserve compatibility with opt-in Core target binding Dec 2, 2026
@NeverENG NeverENG changed the title fix(gateway): preserve compatibility with opt-in Core target binding fix(gateway): preserve legacy behavior with explicit compatibility warnings Dec 2, 2026

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed b53e544 against current master. Default compatibility deliberately preserves the existing URL/proxy behavior and now reports its trust boundary. Required mode remains fail-closed through discovery, initial admission and retries, including subscription destination checks and disabled degradation. Empty keys and invalid mode/proxy configuration are rejected.

The required-mode real Core/Gateway flow with the configured model returned 200 for an approved request, rejected a different model, and sent no bytes to the alternate client-supplied destination. No new database tables are introduced; the explicit deployment settings and additive target contract are reasonable. This PR remains a partial implementation of #2460, as its description states.

Merge confidence: 80/100. Gateway CI passes; two macOS jobs were cancelled and the aggregate CI remains failing. This approval does not replace those outstanding checks.

@hireview001

Copy link
Copy Markdown
Collaborator

The affected modules are Gateway, Core. @frf12, please coordinate follow-up. Gateway: @frf12 @happy-v587 @NeverENG; Core: @hidb4ai @frf12 @Fengzdadi @beatenevo. Please coordinate the review of the affected changes.

@hireview001
hireview001 requested a review from frf12 December 2, 2026 18:36
@NeverENG
NeverENG requested a review from AlexStocks December 3, 2026 02:36

@NeverENG NeverENG left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed head 1d0b539ca02d702097973b8bc4799ce60f114ec5 (32-file diff), focusing on startup negotiation, both model routes and extraction, initial/retry admission, subscription destination assertions, degradation, proxy configuration, and the related tests/deployment guidance.

No additional actionable finding from this source review. Several earlier comments describe superseded behavior: required mode now rejects Claude CLI before listening, invalid target-binding values fail startup, an explicitly empty Gateway key is rejected, and the required-binding requirement is enforced again on retry. Compatible mode deliberately keeps configured destinations and ambient proxies, with explicit warnings and a direct override; the PR correctly limits its claim instead of treating these sends as bound. Loopback with an omitted key remains an explicitly documented compatibility choice.

The latest increment adds the destination-source documentation and Chat/Responses fixture cases for missing/invalid initial targets, missing retry targets, and a fresh retry target with its matching release binding. It introduces no production-code change relative to the preceding reviewed head.

Validation remains incomplete: current-head CI preflight checked out merge f3737286 of this head with base 2886be5d, then failed make check / workflow-actions-check because a locked uv.lock was stale. I have not attributed that failure to this PR's code. Gateway validation and the other dependent jobs were skipped, not passed. I did not run PR code locally or independently exercise real providers/subscriptions; the newly added scripted verdict cases are not real-Core acceptance. Earlier-head green runs do not validate this head. The overlapping identity/readiness changes in #2912 still need validation on the combined result. Comment-only review; no merge approval.

@happy-v587 happy-v587 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed the compatible-mode upgrade paths and required-mode setup on 78c9b1d8 using real Gateway and Core processes with a local model fixture. The inline findings cover two upgrade regressions, explicit proxy validation, and two required-mode deployment failures.

let (default_chat, default_responses) = subscription_kind
.map(pc_gateway_auth::Subscription::default_targets)
.unwrap_or(("http://127.0.0.1:9000/v1/chat/completions", ""));
.unwrap_or(("", ""));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Preserve the default Chat upstream in compatible mode

An existing standalone deployment with a local upstream on port 9000 and no upstream URL or subscription settings changes behavior on upgrade. Against the same real Core and loopback upstream fixture, the base returned HTTP 200 and this head returned 501 chat_route_disabled. Please retain the previous Chat default in compatible mode when both URL settings are absent.

}
let upstream_proxy = match std::env::var("PC_GATEWAY_UPSTREAM_PROXY") {
Ok(value) if value.trim().eq_ignore_ascii_case("direct") => Some(None),
Ok(value) => match reqwest::Proxy::all(value.trim()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Reject unsupported explicit proxy schemes at startup

The startup check accepts an explicit proxy URL with an unsupported scheme, and /healthz returns 200. In the locked HTTP client, the matcher discards the unsupported proxy and the connector falls through to direct egress. That breaks the configured routing policy. Please reject any explicit proxy scheme unsupported by this build before listening. The startup behavior was reproduced locally, and the egress consequence follows from the pinned dependency source.

// v1.6.0 没有 PC_GATEWAY_CORE_TOKEN:允许缺失(不带认证头),存在时才校验。
let core_token = core_token.filter(|token| !token.trim().is_empty());
if let Some(token) = &core_token {
if !authentication::is_bearer_token(token) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve valid legacy Core token formats

A header-safe Core token containing a colon authenticated against the real Core and completed a Chat request with HTTP 200 on the base. On this head, the same compatible-mode configuration exits at startup because it applies the Gateway API key character rules to the separate Core token. Please preserve Core-accepted token formats while validating that the authorization header can be sent safely.

// Upgrading Core alone must not migrate existing model routes. Required mode
// confirms capability and identity and stays required for every admission.
let target_posture = if target_binding_required {
if resolve_target_binding(core_link.clone(), capabilities.as_ref()).await

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Validate the Core transport before starting in required mode

With the same real Core and service identity, required mode completes a model call with HTTP 200 using a literal loopback address. Changing only the Core URL host to localhost still passes discovery and /healthz, but the model call returns 503 malformed_gate_response. The HTTPS or literal-loopback check first runs at admission. Please validate the effective Core transport before sending startup discovery requests, and document the supported transports.


Compatibility warnings do not establish destination equality. Required mode binds each admitted send to its Core-resolved endpoint; this does not prove exclusive delivery through proxies or provider account/region identity. See [the target-binding requirements](https://github.com/oceanbase/powercontext/issues/2460) for the broader contract.

Set `PC_GATEWAY_TARGET_BINDING=required` to use Core as the destination source. Core must advertise `powercontext.context-target.v1`, have target profiles in its inference protection configuration, and run enforced access control. `PC_GATEWAY_CORE_TOKEN` must authenticate an enforced service principal with `server.observe` (`server.observer`) on the Server and `gateway.invoke` (`gateway.user`) on every requested Scope. Capture additionally needs `scope.contribute`, for example through `scope.contributor`. Configure matching endpoint, model and protocol values in each Core profile. Chat uses `PC_GATEWAY_UPSTREAM_PROFILE` (default `default`); Responses uses `PC_GATEWAY_UPSTREAM_PROFILE_RESPONSES` and otherwise the Chat profile name. Use separate profiles when serving different protocols.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Document the required scope.read permission

A dedicated service identity with only the documented server.observer and gateway.user roles passed startup discovery against real Core, then the model request returned HTTP 503 after Core denied the check with HTTP 403. Adding scope.viewer on the same Scope restored HTTP 200. Please list scope.read, for example via scope.viewer, in both locales. Chinese counterpart

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

module:core Core: PR changes under src/ module:gateway Primary module: model gateway, protocols and context injection

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants